﻿using System;
using System.Web;
using Microsoft.SharePoint;
using Redirection.Helpers;

namespace Redirection
{
    public class RedirectionService
        : IRedirectionService, IDisposable
    {
        private readonly ICacheService _cacheService;
        private RedirectionInfo _info;
        private HttpContext _ctx;

        public RedirectionService(SPSite site, HttpContext context)
        {
            Site = site;
            _cacheService = new CacheService(site,context);
            _ctx = context;

            if (RedirectionActive())
            {
                EnsureRedirectionCache();
            }
        }

        public SPSite Site { get; set; }

        public void Dispose()
        {
            _cacheService.Dispose();
        }

        public bool RequiresRedirect(HttpRequest request)
        {
            return RequiresRedirect(request.Path);
        }

        public bool RequiresRedirect(string requestedPath)
        {
            var cache = _cacheService.RedirectionCache;
            if (cache != null && cache.ContainsKey(requestedPath))
            {
                _info = cache[requestedPath];
            }
            return _info != null;
        }

        public void Redirect()
        {
            if (_info == null) return;

            if (!_info.IsPermanent)
            {
                _ctx.Response.Redirect(_info.Destination, true);
            }
            else
            {
                _ctx.Response.RedirectPermanent(_info.Destination, true);
            }
        }

        public bool RedirectionIsActivated
        {
            get
            {
                return RedirectionActive();
            }
        }

        private bool RedirectionActive()
        {
            var isEnabled = false;
            SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (var elSite = new SPSite(Site.ID))
                    {
                        try
                        {
                            var value = elSite.RootWeb.Features[ConstantsService.Features.RedirectionSiteFeature];
                            isEnabled = value != null;
                        }
                        catch
                        {
                        }
                    }
                });
            return isEnabled;
        }

        public void EnsureRedirectionCache()
        {
            if (_cacheService.RedirectionCache == null)
            {
                _cacheService.CreateCache();
            }
        }
    }

    public interface IRedirectionService
    {
        bool RedirectionIsActivated { get; }
        bool RequiresRedirect(HttpRequest request);
        bool RequiresRedirect(string requestedPath);

        void EnsureRedirectionCache(); 
        void Redirect();
    }
}